package com.gzsxy.esjy.service.auth.shiro.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzsxy.esjy.service.base.dto.response.DefaultResponse;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangxiaolong
 * @Description: 限制应用中的资源能否被访问的filter
 *               先调用isAccessAllowed，如果返回的是true，则直接放行执行后面的filter和servlet，
 *                                    如果返回的是false，则继续执行后面的onAccessDenied方法，
 *                                    如果后面返回的是true则也可以有权限继续执行后面的filter和servelt。
 *               只有两个函数都返回false才会阻止后面的filter和servlet的执行。
 * @date 2022/1/5 12:45
 */
public class UserFilter extends AccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception {
        if (isLoginRequest(request, response)) {
            return true;
        }
        Subject subject = getSubject(request, response);
        return subject.getPrincipal() != null;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
         HttpServletResponse servletResponse = WebUtils.toHttp(response);
        servletResponse.setStatus(HttpStatus.OK.value());
        servletResponse.setCharacterEncoding("UTF-8");
        servletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("message","登录过期");
        map.put("code",500);
        map.put("timestamp",String.valueOf(System.currentTimeMillis()));
        ObjectMapper objectMapper = new ObjectMapper();
        //数据直接写入到输出流中
        objectMapper.writeValue(servletResponse.getOutputStream(),map);
        return false;
    }
}
